package ks.app.smartDic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Locale;

import net.daum.mobilead.MobileAdView;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class TTS extends Activity implements OnClickListener {

	private static final int MY_DATA_CHECK_CODE = 4321;
	private static final int DIALOG_MP3 = 2;
	String query, sortOfDictionary;
	private TextToSpeech mTts;

	ImageButton btnBack;
	ImageButton btnHome;
	ImageButton btnTTS;
	ImageButton btnNaver;

	AudioManager am;

	MobileAdView adViewAdam;
	MultipleAd mAd;

	SharedPreferences sp;
	Boolean PrefSuperVolumeCacheing;

	GoogleAnalyticsTracker tracker;

	TextView debugText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tts);

		ksLog.d("TTS Start");

		Intent intent = getIntent();
		sortOfDictionary = intent
				.getStringExtra(getString(R.string.SORT_OF_DICTIONARY));
		query = intent.getStringExtra("query");

		NaverURLManager.setQuery(query);
		NaverURLManager.setSortOfDictionary(sortOfDictionary);

		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnBack.setOnClickListener(this);
		btnHome = (ImageButton) findViewById(R.id.btn_home);
		btnHome.setOnClickListener(this);

		btnTTS = (ImageButton) findViewById(R.id.btn_tts);
		btnTTS.setOnClickListener(this);
		btnNaver = (ImageButton) findViewById(R.id.btn_ttsNAVER);
		btnNaver.setOnClickListener(this);

		sp = getSharedPreferences("PrefSmartDic", 0);
		PrefSuperVolumeCacheing = sp
				.getBoolean("PrefSuperVolumeCacheing", true);

		am = (AudioManager) getSystemService(AUDIO_SERVICE);
		int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);

		SeekBar seekBar = (SeekBar) findViewById(R.id.volumeControl);
		seekBar.setMax(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
		seekBar.setProgress(currentVolume);
		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar arg0) {

			}

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {

			}

			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {

				am.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);

			}
		});

		adViewAdam = (MobileAdView) findViewById(R.id.adviewAdam);

		mAd = new MultipleAd(getApplicationContext(), adViewAdam);
		mAd.displayAd();

		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.start("UA-22873894-1", 20, this);
		tracker.trackPageView("/tts");
		tracker.dispatch();

		debugText = (TextView) findViewById(R.id.debugText);

	}

	@Override
	public void onClick(View v) {
		if (v == btnBack) {

			Intent goTab = new Intent(getApplicationContext(), tabView.class);

			goTab.putExtra(getString(R.string.SORT_OF_DICTIONARY),
					sortOfDictionary);
			goTab.putExtra("query", query);

			startActivity(goTab);

		} else if (v == btnHome) {

			Intent goHome = new Intent(getApplicationContext(), smartDic.class);
			startActivity(goHome);

		} else if (v == btnTTS) {

			startTTSActivity();

		} else if (v == btnNaver) {

			ksLog.d("btnNaver");
			ksLog.d("btnNaver2");

			backgroundGetMP3 db = new backgroundGetMP3();
			db.execute();

			ksLog.d("btnNaver3");
			ksLog.d(db.parsedUrl);

		}

	}

	public class Downloader {

		public void DownloadFile(String fileURL, String fileName) {
			try {

				File sdCard = Environment.getExternalStorageDirectory();
				File dir = new File(sdCard.getAbsolutePath() + "/smartDic/");
				dir.mkdirs();
				File file = new File(dir, fileName);

				URL u = new URL(fileURL);
				HttpURLConnection c = (HttpURLConnection) u.openConnection();
				c.setRequestMethod("GET");
				c.setDoOutput(true);
				c.connect();

				FileOutputStream f = new FileOutputStream(file);

				InputStream in = c.getInputStream();

				byte[] buffer = new byte[1024];
				int len1 = 0;
				while ((len1 = in.read(buffer)) > 0) {
					f.write(buffer, 0, len1);
				}
				f.close();
			} catch (Exception e) {
				ksLog.d("Downloader", e.getMessage());
			}

		}
	}

	private class backgroundGetMP3 extends AsyncTask<String, String, String> {

		MediaPlayer mp;
		Downloader dn = new Downloader();
		FileInputStream inputStreamForPlay;

		httpClient hp;
		jerichoParser jp;
		InputStream http_data;

		private static final int STATUS_NONE = 0;
		private static final int STATUS_CACHED = 1;
		private static final int STATUS_GET_URL = 2;
		private static final int STATUS_NO_URL = 3;
		int playStatus = STATUS_NONE;
		private static final int MODE_DEFINITION = 1;

		String parsedUrl = null;

		@Override
		protected String doInBackground(String... params) {

			mp = new MediaPlayer();

			String mp3Url = null;

			try {
				mp3Url = "http://endic.naver.com/search.nhn?query="
						+ URLEncoder.encode(query, "UTF-8");
			} catch (Exception e) {

			}

			try {

				if (isExist(query) && PrefSuperVolumeCacheing) {
					mp.setDataSource(inputStreamForPlay.getFD());
					playStatus = STATUS_CACHED;
				} else {
					hp = new httpClient();
					jp = new jerichoParser();
					http_data = hp.post(mp3Url);
					String url = jp.getMP3Url(http_data);

					parsedUrl = url;

					if (url != null) {
						dn.DownloadFile(url, query + ".lks");
						playStatus = STATUS_GET_URL;
					} else
						playStatus = STATUS_NO_URL;

					if (playStatus != STATUS_NO_URL) {
						mp.setDataSource(url);
						tracker.setCustomVar(1, "TTS_SUCCESS", query, 1);
					} else {
						tracker.setCustomVar(1, "TTS_FAIL", query, 1);
					}
					tracker.dispatch();
				}

				if (playStatus != STATUS_NO_URL) {
					mp.prepare();

				}

			} catch (Exception e) {

			}
			return null;
		}

		protected void onProgressUpdate(String... values) {

		}

		@Override
		protected void onPreExecute() {

			showDialog(DIALOG_MP3);

		}

		protected void onPostExecute(String result) {

			ksLog.d("parsedUrl", parsedUrl);

			removeDialog(DIALOG_MP3);

			String message = null;

			if (playStatus != STATUS_NO_URL) {

				if (playStatus == STATUS_CACHED) {

					message = "내 폰에서 PLAY";

				} else {

					message = "인터넷에서 PLAY";
				}

				Toast.makeText(getApplicationContext(), message,
						Toast.LENGTH_LONG).show();
				mp.start();

			} else {

				message = "발음이 존재하지 않습니다.";
				Toast.makeText(getApplicationContext(), message,
						Toast.LENGTH_LONG).show();

			}
			
			debugText.setText(message);

			ksLog.d("message", message);

		}

		private Boolean isExist(String query) {

			File sdCard = Environment.getExternalStorageDirectory();
			File dir = new File(sdCard.getAbsolutePath() + "/smartDic/");
			dir.mkdirs();
			File file = new File(dir, query + ".lks");

			if (file.exists()) {
				try {
					inputStreamForPlay = new FileInputStream(file);

					return true;
				} catch (Exception e) {
					return false;
				}

			}

			return false;

		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_MP3: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("잠시만 기다려 주세요...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

	void startTTSActivity() {

		mTts = new TextToSpeech(this, null);
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == MY_DATA_CHECK_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {

				// success, create the TTS instance
				play();

				mAd.displayAd();

			} else {

				// missing data, install it
				Intent installIntent = new Intent();
				installIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);

			}
		}
	}

	private void play() {
		mTts.setLanguage(Locale.US);
		mTts.speak(query, TextToSpeech.QUEUE_FLUSH, // Drop all pending entries
													// in the playback queue.
				null);
	}

	protected void onResume() {

		super.onResume();

		mAd.displayAd();

	}
}
